/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.authorization.manager.impl;

import com.bifrost.authorization.interceptor.AuthorizationInterceptor;
import com.bifrost.authorization.manager.TokenManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 通过Redis存储和验证token的实现类
 *
 * @author bifrost
 * @version 1.0.0
 * @Date 2017/10/9 10:56
 * @see TokenManager
 */
@Component
public class RedisTokenManager implements TokenManager {

    private static final Logger logger = LoggerFactory.getLogger(RedisTokenManager.class);
    @Value("${jwt.token.key}")
    private String key;

    @Value("${jwt.token.expire}")
    private Long expire;

    private RedisTemplate<Long, String> redis;

    @Autowired
    @Qualifier("redisTemplate")
    public void setRedis(RedisTemplate redis) {
        this.redis = redis;
        //泛型设置成Long后必须更改对应的序列化方案
        redis.setKeySerializer(new JdkSerializationRedisSerializer());
    }

    /**
     * 创建一个token关联上指定用户
     *
     * @param uid 指定用户的id
     * @return 生成的token
     */
    @Override
    public String createToken(long uid) {
        long nowMillis = System.currentTimeMillis();
        JSONObject payload = new JSONObject();
        payload.put("uid", uid);
        payload.put("scope", "ALL");
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder()
                .setIssuedAt(now)
                .setSubject(payload.toJSONString())
                .setIssuer("MALL")
                .signWith(SignatureAlgorithm.HS256, key);
        //Builds the JWT and serializes it to a compact, URL-safe string
        String token = builder.compact();
        redis.boundValueOps(uid).set(token, expire, TimeUnit.DAYS);
        return token;
    }

    /**
     * 检查token是否有效
     *
     * @param token 待验证的token
     * @return 是否有效
     */
    @Override
    public boolean checkToken(String token, HttpServletRequest request) {
        try {
            if (token == null) {
                return false;
            }
            String s = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject();
            JSONObject json = JSONObject.parseObject(s);
            if (json.containsKey(AuthorizationInterceptor.UID)) {
                long uid = json.getLong(AuthorizationInterceptor.UID);
                String redisToken = redis.boundValueOps(uid).get();
                if (redisToken == null || !redisToken.equals(token)) {
                    return false;
                } else {
                    //redis.boundValueOps(uid).set(token, expire, TimeUnit.DAYS);
                    //如果token验证成功，将token对应的用户id存在request中，便于之后注入
                    request.setAttribute(AuthorizationInterceptor.UID, uid);
                    return true;
                }

            } else {
                return false;
            }
        } catch (SignatureException e) {
            throw e;
        } catch (ExpiredJwtException e1) {
            throw e1;
        }
    }

    /**
     * 从字符串中解析token
     *
     * @param authentication 加密后的字符串
     * @return
     */
    @Override
    public String getToken(String authentication) {
        return null;
    }

    /**
     * 清除token
     *
     * @param userId 登录用户的id
     */
    @Override
    public void deleteToken(long userId) {
        redis.delete(userId);
    }
}
